/**
 * 
 */
package com.kebo2.client;

/**
 * @author Tim
 *
 */

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootLayoutPanel;

public class HttpRequest {
	
public void getMessageXml(String file, String type, String requestData, final AsyncCallback<String> callback) {
		
		RootLayoutPanel.get().addStyleName("loading");
		
		final String url = "php/" + file;
		RequestBuilder rb;

		try {
			if(type == "POST") 
				rb = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
			else 
				rb = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
			
			rb.setHeader("Content-Type", "application/x-javascript; charset:ISO-8859-1");
			rb.sendRequest(requestData, new RequestCallback() {

				@Override
				public void onResponseReceived(Request request, Response response) {
					
					if(Response.SC_OK == response.getStatusCode()) {
						
						if(response.getText().equals(Integer.toString(666))) {
							UserInterface.closeWindow();
							UserInterface.clearIcons();
							Window.alert("Je logingegevens zijn verlopen. Je moet opnieuw inloggen.");
							Window.Location.reload();
						}
						else 
							callback.onSuccess(response.getText());	
					}
					else 
						Window.alert(Kebo2.error.INTERNET_CONNECTION);
					
					RootLayoutPanel.get().removeStyleName("loading");	
				}

				@Override
				public void onError(Request request, Throwable exception) {	
					callback.onFailure(exception);
				}	
			});	
		}
		catch(RequestException rex) {
			callback.onFailure(rex);
		}	
	}
}
